<?php
/*
	Required for giving fresh data every fucking time.
*/
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');  
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');  

require 'vendor/autoload.php';

$app = new \Slim\Slim(array(
     'debug' => true
));

//$db = new PDO('mysql:host=karans-iMac.local;dbname=alcohol', 'admin', 'admin');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$app->get('/users(/:username)', 'getUser');
$app->get('/beers(/:id)', 'getBeers');
$app->get('/scotches(/:id)', 'getScotches');
$app->get('/bars(/:id)', 'getBars');
$app->get('/', 'getBars');

$app->post('/add/user', 'addUser')->name('add_user')->via('GET', 'POST');
$app->post('/login', 'login');
$app->post('/add/drinks', 'addUserDrinks');

//$app->post('/add_beer', 'addBeer');
//$app->post('/add_scotch', 'addScotch');
//$app->post('/add_bar', 'addBar');


function getConnection() {
    //$dbhost="karans-iMac.local";
    $dbhost="localhost";
    $dbuser="admin";
    $dbpass="admin";
    $dbname="alcohol";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}

function getUser($id = '') {
	$sql = "select * from user";
	if(!empty($id)) {
		$sql .= " where username = '$id'";
	}

	try {
	$db = getConnection();	
	$stmt = $db->query($sql);
	$result =  $stmt->fetchAll(PDO::FETCH_OBJ);
        header('Content-Type: application/json');
        header("Access-Control-Allow-Origin: *");        
	echo '{"users": ' . json_encode($result) . '}';
	$db = null;
	} catch (PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
	}
}

function getBeers($id = '') {
	$sql = "select * from beer";
	if(!empty($id)) {
		$sql .= " where id = '$id'";
	}
	
	try {
	$db = getConnection();	
	$stmt = $db->query($sql);
        header('Content-Type: application/json');
        header("Access-Control-Allow-Origin: *");        
	$result =  $stmt->fetchAll(PDO::FETCH_OBJ);
	echo '{"beers": ' . json_encode($result) . '}';
	$db = null;
	} catch (PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
	}
}


function getScotches($id = '') {
	$sql = "select * from scotch";
	if(!empty($id)) {
		$sql .= " where id = '$id'";
	}
	
	try {
	$db = getConnection();	
	$stmt = $db->query($sql);
	$result =  $stmt->fetchAll(PDO::FETCH_OBJ);
    header('Content-Type: application/json');
    header("Access-Control-Allow-Origin: *");
	echo '{"scotches": ' . json_encode($result) . '}';
	$db = null;
	} catch (PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
	}
}

function getBars($id = '') {
	$sql = "select bar.name, address.street, address.city, address.zip, address.country from bar inner join address on bar.address_id = address.id ";
	if(!empty($id)) {
		$sql .= " where bar.id = '$id'";
	}
	
	try {
	$db = getConnection();	
	$stmt = $db->query($sql);
	$result =  $stmt->fetchAll(PDO::FETCH_OBJ);
        header('Content-Type: application/json');
        header("Access-Control-Allow-Origin: *");
	echo '{"bar": ' . json_encode($result) . '}';
	$db = null;
	} catch (PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}';
	}
}

function addUser() {
      $request =  \Slim\Slim::getInstance()->request();
      $user = json_decode($request->getBody());
      $sql = "select * from user where username = '". $user->username."' limit 1";
      header('Cache-Control: no-cache, no-store, must-revalidate');
      header('Pragma: no-cache');
      header('Expires: 0');  
      header('Content-type: text/json');          
      $res = getResults($sql);
      if(empty($res)) {
          echo "Invalid user credentials";
      } else {
      	echo "Login Successful";
      }
}

function addBar() {
    $request =  \Slim\Slim::getInstance()->request();
    $user = json_decode($request->getBody());
    print_r($request);
}

function getResults($sql) {
    try {
	$db = getConnection();	
	$stmt = $db->query($sql);
	$result =  $stmt->fetchAll(PDO::FETCH_ASSOC);
	$db = null;
        return $result;
        
    } catch (PDOException $e) {
        return $e->getMessage();
    }
}


function login() {
	$request =  \Slim\Slim::getInstance()->request();
    $user = json_decode($request->getBody());
	$method = $request->getMethod();
    error_log("In login function");
	if($method == 'POST') {
		$username= $request->post('username');
	   	$password = $request->post('password');
	}
    $sql = "select * from user where username = '". $username."' and password = '".$password."' limit 1";
    $res = getResults($sql);
    error_log($sql);
    if(empty($res)) {
        error_log("false");
        echo "false";

    } else {
        error_log("true");
    	echo "true";
    }
    //print_r($res);
    //echo $output;
    //return $output;
}


/**
Expected Values, user id, bar name / bar id and drink.
TODO: Add a validation token so verify authenticity of the post.
*/
function addUserDrinks() {
	$request =  \Slim\Slim::getInstance()->request();
    $method = $request->getMethod();

    if($method == 'POST') {
    	$user_id = $request->post('user_id');
    	$bar_id = $request->post('bar_id');
    	$drink = $request->post('drink');
    }

    //1. Check if user_id, bar_id row exists.
    $check_entry = "select user_id, bar_id, drinks from userdiary where user_id = '".$user_id."' and bar_id = '".$bar_id."' and timestamp = CURDATE() limit 1";
    $res = getResults($check_entry);

    if(empty($res[0])) {
    	$insert = "insert into userdiary (user_id, bar_id, drinks, timestamp) values ('".$user_id."', '".$bar_id."', '".$drink."', CURDATE())";
    	try{
    		$db = getConnection();	
			$stmt = $db->query($insert);
			$db = null;
    	 } catch (PDOException $e) {
        	echo $e->getMessage();
    	}
    } else {
    	$drinks = $res[0]['drinks'].",$drink";
    	print_r($drinks);
    	$sql = "update userdiary set drinks = '".$drinks."' where user_id = '".$user_id."' and bar_id = '".$bar_id."' and timestamp = CURDATE()";
    	try{
    		$db = getConnection();	
			$stmt = $db->query($sql);
			$db = null;
    	 } catch (PDOException $e) {
        	return $e->getMessage();
    	}
    	print_r(getResults($check_entry));
    }
}


$app->run();

?>


